
use std::fs;
use std::path::PathBuf;
use std::path::Path;

use crate::command_parser;
mod repo_error;
mod utils;


use repo_error::RepoError as RepoError;

static g_grepo_path: &str = ".grepo";
static g_manifest_git_dir: &str = "manifests.git";
static g_manifest_git_path: &str = ".grepo/manifests.git";
static g_manifest_path: &str = ".grepo/manifests";
static g_project_path: &str = ".grepo/projects";

fn do_dir_create(path:&str) -> Result<(), Box<dyn std::error::Error>> {
    fs::create_dir(PathBuf::from(path))?;
    Ok(())
}


fn check_init_param(param: &command_parser::CommandInit) -> bool {
    println!("got init subcommand, manifest url({:?}), brance({:?})", param.url, param.branch);
    return true;
}

fn repo_dir_init(param: &command_parser::CommandInit) -> Result<(), Box<dyn std::error::Error>> {

    if utils::is_dir_exist(g_grepo_path) {
        return Err(Box::new(RepoError::AlreadyExist));
    }

    do_dir_create(g_grepo_path)?;
    do_dir_create(g_manifest_git_path)?;
    do_dir_create(g_manifest_path)?;
    do_dir_create(g_project_path)?;



    return Ok(());
}


fn pull_manifest_repo(param: &command_parser::CommandInit) -> Result<(), Box<dyn std::error::Error>> {

    Ok(())
}



pub fn do_init(param: command_parser::CommandInit) -> Result<(), Box<dyn std::error::Error>> {
    println!("got init subcommand, manifest url({:?}), brance({:?})", param.url, param.branch);
    if check_init_param(&param) {
        
        if !utils::is_git_installed() {
            return Err(Box::new(RepoError::Undefined));
        }

        repo_dir_init(&param)?;


        return Ok(());
    } 
    
    return Err(Box::new(RepoError::InvalidArgument));
}